package com.xwb.config;

import com.xwb.entity.User;
import com.xwb.service.UserService;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {
    @Autowired
    UserService userService;


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了=>授权");

        //SimpleAuthorizationInfo
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//        info.addStringPermission("user:add");

        //拿到当前登录的这个对象
        Subject subject = SecurityUtils.getSubject();
        User currentUser=(User)subject.getPrincipal();//拿到User对象
        info.addRole(Integer.toString(currentUser.getAdministrator()));

        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了=>认证");

        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        //连接真实的数据库
        User user=userService.queryUserByName(userToken.getUsername());
        if(user==null){//没有这个人
            return null;//UnkownAccountException
        }

        //密码认证，shiro做
        return new SimpleAuthenticationInfo(user,user.getPassword(),"");

//        //用户名，密码~  数据中取
//        String name ="123";
//        String password="123";
//        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
//        if(!userToken.getUsername().equals(name)){
//            return null;//抛出异常 UnknowAccountException
//        }
//        //密码认证，shiro做~
//        return new SimpleAuthenticationInfo("",password,"");


    }
}
